﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp6
{
    public class ChunkWriter
    {
        private Chunk _currentChunk;
        private readonly ChunkManager _chunkManager;
        private readonly ICheckPoint _writeCheckPoint;
        public ChunkWriter(ChunkManager chunkManager)
        {
            _chunkManager = chunkManager;
            _currentChunk = _chunkManager.GetCurrentChunk();
            _writeCheckPoint = _chunkManager.Config.WriterCheckPoint;
        }

        public MessageWriteResult WriteMessage(IMessageExt msgExt)
        {
            var result = _currentChunk.Append(msgExt);
            if (result.Success)
            {
                _writeCheckPoint.Write(result.NewPosition);
            }
            if (!result.Success)
            {
                SwitchToNewChunk();
                // 尝试再次写入
                result = _currentChunk.Append(msgExt);
                if (!result.Success)
                {
                    throw new Exception("Failed to write to the new chunk as well.");
                }
            }

            return result;
        }

        // 可选：增加切换chunk的方法，当Append失败时调用
        public void SwitchToNewChunk()
        {
            _currentChunk.Flush();
            // 当前chunk已满，创建并切换到新的chunk
            _currentChunk = _chunkManager.CreateNewChunk();
        }
    }
}
